using Cysharp.Threading.Tasks;
using System;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class PlayerStatusPanel : UIPanelBase
{
    [SerializeField]
    private Slider m_HPSlider, m_EnergySlider, m_StaminaSlider;

    private IDisposable m_TotalHPListener, m_CurrentHPListener, 
        m_EnergyCapacityListener, m_CurrentEnergyListener, 
        m_StaminaCapacityListener, m_CurrentStaminaListener;

    protected async override void OnInit()
    {
        await UniTask.WaitUntil(() => SceneOrganizer.playerInstance != null);
        Show();
    }

    protected override void OnShow()
    {
        var attribute = SceneOrganizer.playerInstance.attribute as PlayerAttribute;
        m_TotalHPListener = attribute.onTotalHP.Subscribe(v => m_HPSlider.maxValue = (float)v);
        m_CurrentHPListener = attribute.onCurrentHP.Subscribe(v => m_HPSlider.value = (float)v);
        m_EnergyCapacityListener = attribute.onEnergyCapacity.Subscribe(v => m_EnergySlider.maxValue = v);
        m_CurrentEnergyListener = attribute.onCurrentEnergy.Subscribe(v => m_EnergySlider.value = v);
        m_StaminaCapacityListener = attribute.onStaminaCapacity.Subscribe(v => m_StaminaSlider.maxValue = v);
        m_CurrentStaminaListener = attribute.onCurrentStamina.Subscribe(v => m_StaminaSlider.value = v);

        Refresh();
    }

    protected override void OnHide()
    {
        m_TotalHPListener?.Dispose();
        m_CurrentHPListener?.Dispose();
        m_EnergyCapacityListener?.Dispose();
        m_CurrentEnergyListener?.Dispose();
        m_StaminaCapacityListener?.Dispose();
        m_CurrentStaminaListener?.Dispose();
    }

    private void Refresh()
    {
        var attribute = SceneOrganizer.playerInstance.attribute as PlayerAttribute;
        m_HPSlider.maxValue = (float)attribute.totalHP;
        m_HPSlider.value = (float)attribute.currentHP;
        m_EnergySlider.maxValue = attribute.energyCapacity;
        m_EnergySlider.value = attribute.currentEnergy;
        m_StaminaSlider.maxValue = attribute.staminaCapacity;
        m_StaminaSlider.value = attribute.currentStamina;
    }
}
